using System.Windows;
using System.Windows.Controls;

namespace Controls
{
	public class TabItemCloseable : TabItem
	{
		public static readonly DependencyProperty ImageSourceProperty;

		public static readonly RoutedEvent CloseTabEvent;

		public string ImageSource
		{
			get
			{
				return (string)GetValue(ImageSourceProperty);
			}
			set
			{
				SetValue(ImageSourceProperty, value);
			}
		}

		public event RoutedEventHandler CloseTab
		{
			add
			{
				AddHandler(CloseTabEvent, value);
			}
			remove
			{
				RemoveHandler(CloseTabEvent, value);
			}
		}

		static TabItemCloseable()
		{
			ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(string), typeof(TabItemCloseable));
			CloseTabEvent = EventManager.RegisterRoutedEvent("CloseTab", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TabItemCloseable));
			FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(TabItemCloseable), new FrameworkPropertyMetadata(typeof(TabItemCloseable)));
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			Button button = GetTemplateChild("PART_Close") as Button;
			if (button != null)
			{
				button.Click += closeButton_Click;
			}
		}

		private void closeButton_Click(object sender, RoutedEventArgs e)
		{
			RoutedEventArgs routedEventArgs = new RoutedEventArgs(CloseTabEvent, this);
			RaiseEvent(routedEventArgs);
			if (!routedEventArgs.Handled)
			{
				((TabControl)base.Parent).Items.Remove(this);
			}
		}
	}
}
